import {
  BaseCommand,
  CommandDialog,
  getQueryParam,
  http,
  QueryParamKeys,
} from '@amcax/base';
import { useEffect, useState } from 'react';
import { Vector3 } from 'three-legacy';
import { Button, Input, Image, Checkbox } from 'antd';
import './index.scss';
import { AirFormDataLike, cmdAirfoilAPI } from './cmdAirfoilAPI';
import { MessageTip } from '@app-base/common/utils';

// 翼型
interface AirfoilCommandProps {
  title: string;
  onClose: () => void;
}

const documentId = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);
function AirfoilCommand({ title, onClose }: AirfoilCommandProps) {
  /**几何信息*/
  const [airFormData, setAirFormData] = useState<AirFormDataLike>({
    camber_max: 0.02,
    camber_max_pos: 0.3,
    thickness_max: 0.12,
    thickness_max_pos: 0.3,
    leading_radius_index: 8,
    lift_angle: 0,
    mach_number: 0.785,
    reynolds_number: 5e6,
  });
  const [createCurve, setCreateCurve] = useState<boolean>(true);
  const [createPoint, setCreatePoint] = useState<boolean>(false);

  useEffect(() => {
    if (createCurve === false && createPoint === false) {
      MessageTip.warning('必须至少启用一个选项');
      setCreateCurve(true);
    }
  }, [createCurve, createPoint]);

  const handleAirFormDataChange = () => (event) => {
    const { name, value } = event.target;
    if (isNaN(value)) {
      return;
    }
    setAirFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const checkAirformData = (minValue, maxValue) => (event) => {
    const { name, type } = event.target;
    let { value } = event.target;
    if (type === 'number') value = Number(value);
    if (isNaN(value)) {
      return;
    }
    if (value < minValue) {
      value = minValue;
    } else if (value > maxValue) {
      value = maxValue;
    }
    setAirFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const createAirfoil = async () => {
    await executeCmdAirfoil();
    onClose();
  };

  /**
   * 生成翼型
   * 请求接口 获取翼型数据 进入生成命令
   */
  const executeCmdAirfoil = async () => {
    const params = {
      camber_max: airFormData.camber_max,
      camber_max_pos: airFormData.camber_max_pos,
      thickness_max: airFormData.thickness_max,
      thickness_max_pos: airFormData.thickness_max_pos,
      leading_radius_index: airFormData.leading_radius_index,
    };

    const generateAddr = `https://next-dev.amcax.net/airfoil/v1/${documentId}/generate`;

    const res = await http.post(generateAddr, params);

    const jsonPoints = JSON.stringify(res.data.data);
    const pointsPos = JSON.parse(jsonPoints);
    const paramData = pointsPos.map(
      (item: any) => new Vector3(item.x, item.y, 0),
    );

    await cmdAirfoilAPI.invoke(paramData, createCurve, createPoint);
  };

  const cancel = () => {
    onClose();
  };

  return (
    <CommandDialog
      title={title}
      onClose={onClose}
      placement='topLeft'
    >
      <div className='box'>
        <div className='meun-panel'>
          <div className='meun-panel1'>
            <Image
              src={process.env.PUBLIC_URL + '/images/airfoil.png'}
              style={{ width: '290px' }}
            />
            <div className='menu-child'>
              <div className='menu-child1'>前缘半径指数(R)</div>
              <div className='input1'>
                <Input
                  name='leading_radius_index'
                  type='number'
                  min='0.8'
                  max='8.0'
                  step='0.1'
                  value={airFormData.leading_radius_index}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.8, 8.0)}
                  onClick={(e) => e.stopPropagation()}
                />
              </div>
            </div>

            <div className='menu-child'>
              <div className='menu-child1'>最大厚度(T)</div>
              <div className='input1'>
                <Input
                  name='thickness_max'
                  type='number'
                  min='0.04'
                  max='0.4'
                  step='0.01'
                  value={airFormData.thickness_max}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.04, 0.4)}
                  onClick={(e) => e.stopPropagation()}
                />
              </div>
            </div>

            <div className='menu-child'>
              <div className='menu-child1'>最大厚度位置(Xt)</div>
              <div className='input1'>
                <Input
                  name='thickness_max_pos'
                  type='number'
                  min='0.2'
                  max='0.6'
                  step='0.1'
                  value={airFormData.thickness_max_pos}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.2, 0.6)}
                  onClick={(e) => e.stopPropagation()}
                />
              </div>
            </div>

            <div className='menu-child'>
              <div className='menu-child1'>最大弯度(F)</div>
              <div className='input1'>
                <Input
                  name='camber_max'
                  type='number'
                  min='0'
                  max='0.1'
                  step='0.01'
                  value={airFormData.camber_max}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.0, 0.1)}
                  onClick={(e) => e.stopPropagation()}
                />
              </div>
            </div>

            <div className='menu-child'>
              <div className='menu-child1'>最大弯度位置(Xf)</div>
              <div className='input1'>
                <Input
                  name='camber_max_pos'
                  type='number'
                  min='0.1'
                  max='0.9'
                  step='0.1'
                  value={airFormData.camber_max_pos}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.1, 0.9)}
                  onClick={(e) => e.stopPropagation()}
                />
              </div>
            </div>

            <Checkbox
              style={{ marginTop: 8 }}
              checked={createCurve}
              onChange={(e) => setCreateCurve(e.target.checked)}
            >
              自动拟合曲线
            </Checkbox>
            <Checkbox
              style={{ marginTop: 8 }}
              checked={createPoint}
              onChange={(e) => setCreatePoint(e.target.checked)}
            >
              创建点列表
            </Checkbox>
          </div>

          {/* 按钮组 */}
          <div className='button'>
            <div style={{ paddingLeft: '0px', marginRight: '8px' }}>
              <Button
                style={{ borderRadius: '5px' }}
                onClick={cancel}
              >
                取消
              </Button>
            </div>
            <div style={{ paddingRight: '0px' }}>
              <Button
                type='primary'
                style={{ borderRadius: '5px' }}
                onClick={createAirfoil}
              >
                生成
              </Button>
            </div>
          </div>
        </div>
      </div>
    </CommandDialog>
  );
}

export const cmdAirfoil: BaseCommand = {
  id: 'CmdAirfoil',
  label: '创建翼型',
  icon: 'commands/feature/create-airfoil',
  noHighlight: true,
  create: (label: string, onClose: () => void) => (
    <AirfoilCommand
      title={'创建翼型'}
      onClose={onClose}
    />
  ),
};
